package org.dreamwork.jasmine2.parser;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2009-1-22
 * Time: 15:52:27
 */
public final class PageDirective extends JspDirective {
    private static final Pattern p = Pattern.compile ("^@\\s*page\\s+");

    protected PageDirective (String content) {
        super (content);
        type = TYPE_PAGE;
    }

    public void parse () throws ParseException {
        content = content.replaceAll ("[\\s]*=[\\s]*", "=");
        Pattern pattern = Pattern.compile ("^(<%)?@?\\s*page\\s+(.*?)(%>)?$");
        Matcher m = pattern.matcher (content);
        StringBuffer buffer = new StringBuffer ();
        if (m.matches ())
//            content = m.appendReplacement (buffer, "").appendTail (buffer).toString ();
            content = m.group (2);
//        content = content.substring ("@page".length ()).trim ();
        String[] a = content.split ("[\\s]+");
        for (String anA : a) {
            String s = anA.trim ();
            String name, value;
            if (s.startsWith ("contentType")) {
                name = "contentType";
                value = s.substring (name.length () + 1);
            } else if (s.charAt (0) != '<') {
                String[] t = anA.trim ().split ("=");
                if (t.length != 2) throw new ParseException ("Attribute error! [" + anA + "]");
                name = t[0];
                value = t[1];
            } else
                continue;
            char first = value.charAt (0);
            char last = value.charAt (value.length () - 1);
            if (first == '\'' || first == '"') {
                if (first != last)
                    throw new ParseException ("Attribute error! must well format");
                value = new String (value.toCharArray (), 1, value.length () - 2);
            }
            setAttribute (name, value);
        }
    }

    public String toString () {
        StringBuilder buff = new StringBuilder ("<%@page");
        for (String key : getAttributes ().keySet ()) {
            buff.append (" ");
            buff.append (key).append ("=\"").append (getAttribute (key)).append ("\"");
        }
        buff.append ("%>");
        return buff.toString ();
    }
}
